﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HRM.HRMServiceProxy;


namespace HRM
{
    public partial class frmSalaryInfo : Form
    {
        DepartmentClient wcfDepartment;
        EmployeeClient wcfEmployee;
        EmployeeInfo _EmployeeInfo;
        PositionDetailClient wcfPD;
        PositionDetailInfo _PDInfo;
        LabourContractClient wcfLC;
        LabourContractInfo _LCInfo;
        int _SalaryID;
        int _EmployeeID;
        SalaryClient wcfSalary;
        SalaryInfo _SalaryInfo;
        DialogResult dlgResult;
        int _month = DateTime.Now.Month;
        int _year = DateTime.Now.Year;
        RoleRightInfo listRole;
        decimal _BasicSalary, _SalaryOneDay;
        bool _Isload = false;
        int _TotalDateWork;
        decimal _EmpSocialIns, _EmpMedicalIns;
        decimal _ComSocialIns, _ComMedicalIns;
        decimal _UnemployedIns;
        decimal _UnemployedInsCompany;
        decimal _FamilySalary;
        decimal _TradeUnion;

        public frmSalaryInfo(int SalaryID, RoleRightInfo _listRole)
        {
            _SalaryID = SalaryID;
            InitializeComponent();
            dlgResult = DialogResult.Cancel;
            ChangeLanguage();

            wcfSalary = Service.Salary();
            wcfEmployee = Service.Employee();
            wcfDepartment = Service.Department();
            dlgResult = DialogResult.Cancel;
            _SalaryInfo = new SalaryInfo();
            cboMonth.Text = DateTime.Now.Month.ToString();
            cboYear.Text = DateTime.Now.Year.ToString();
            _Isload = false;

            ParameterClient wcfParameter = Service.Parameter();
            _BasicSalary = Convert.ToDecimal(wcfParameter.Parameter_GetByName("MinBasicSalary").Value);
            _TotalDateWork = Convert.ToInt32(wcfParameter.Parameter_GetByName("TotalDateWork").Value);
            _FamilySalary = Convert.ToDecimal(wcfParameter.Parameter_GetByName("FamilySalary").Value);
            _SalaryOneDay = Convert.ToDecimal(_BasicSalary / _TotalDateWork);

            _TradeUnion = Convert.ToDecimal(wcfParameter.Parameter_GetByName("TradeUnion").Value) / 100;
            _EmpMedicalIns = Convert.ToDecimal(wcfParameter.Parameter_GetByName("MedicalInsurancePercentLabour").Value) / 100;
            _EmpSocialIns = Convert.ToDecimal(wcfParameter.Parameter_GetByName("SocialInsurancePercentLabour").Value) / 100;

            _ComSocialIns = Convert.ToDecimal(wcfParameter.Parameter_GetByName("SocialInsurancePercent").Value) / 100;
            _ComMedicalIns = Convert.ToDecimal(wcfParameter.Parameter_GetByName("MedicalInsurancePercent").Value) / 100;

            _UnemployedIns = Convert.ToDecimal(wcfParameter.Parameter_GetByName("UnemployedIns").Value) / 100;
            _UnemployedInsCompany = Convert.ToDecimal(wcfParameter.Parameter_GetByName("UnemployedInsCompany").Value) / 100;

            if (_SalaryID > 0)
            {
                _SalaryInfo = wcfSalary.Salary_GetInfo(_SalaryID);
                _EmployeeID = _SalaryInfo.EmployeeID;
                Info2Form();
            }
            listRole = _listRole;

        }

        private void ChangeLanguage()
        {
            if (this.Tag != null)
                this.Text = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
            UpdateUI.Load_Panel(ref panel2);
            UpdateUI.Load_GroupBox(ref groupBox1);
            UpdateUI.Load_GroupBox(ref groupBox2);
            UpdateUI.Load_GroupBox(ref groupBox3);
            UpdateUI.Load_GroupBox(ref groupBox4);
            UpdateUI.Load_GroupBox(ref groupBox5);
            UpdateUI.Load_ToolStrip(ref toolStrip1);
        }

        private void Info2Form()//Hiển thị thông tin ra form
        {
            wcfPD = Service.PositionDetail();
            _EmployeeInfo = new EmployeeInfo();
            _EmployeeInfo = wcfEmployee.Employee_GetInfo(_EmployeeID);
            PositionDetailInfo _PDInfo = new PositionDetailInfo();
            _PDInfo = wcfPD.PositionDetail_GetInfo(_EmployeeID);
            txtDepartment.Text = wcfDepartment.Department_GetInfo(_PDInfo.DepartmentID).Name;
            txtFullName.Text = _EmployeeInfo.LastName + " " + _EmployeeInfo.FirstName;
            txtFullName.Tag = _SalaryInfo.EmployeeID;
            DataTable dt = wcfPD.PositionDetail_GetWithEmployee(_SalaryInfo.EmployeeID).Tables[0];
            txtPosition.Text = dt.Rows[0]["PositionName"].ToString();

            txtProbation.Text = _SalaryInfo.ProbationFactor.ToString(UIParamater.Cham2So);
            txtDateWork.Text = _SalaryInfo.TotalDateWork.ToString(UIParamater.Cham2So);
            txtDateOutWork.Text = _SalaryInfo.TotalDateOutWork.ToString(UIParamater.Cham2So);
            txtOverTime.Text = _SalaryInfo.OverTime.ToString(UIParamater.Cham2So);
            cboMonth.Text = _SalaryInfo.Date.Month.ToString();
            cboYear.Text = _SalaryInfo.Date.Year.ToString();
            txtLeavePaid.Text = _SalaryInfo.TotalLeavePaid.ToString(UIParamater.Cham2So);
            txtLeaveUnPaid.Text = _SalaryInfo.TotalLeaveUnPaid.ToString(UIParamater.Cham2So);
            //txtBasicFactory.Text = _SalaryInfo.BasicFactor.ToString(UIParamater.Cham2So);
            txtBasicSalary.Text = _SalaryInfo.BasicSalary.ToString(UIParamater.Phay2So);
            //txtPositionFactor.Text = _SalaryInfo.PositionFactor.ToString(UIParamater.Cham2So);
            txtPositionAllowance.Text = _SalaryInfo.PositionAllowance.ToString(UIParamater.Phay2So);
            txtOverSeniorityFactor.Text = _SalaryInfo.OverSeniorityFactor.ToString(UIParamater.Cham2So);
            txtSeniorityFactor.Text = _SalaryInfo.SeniorityFactor.ToString(UIParamater.Cham2So);
            txtResponseFactory.Text = _SalaryInfo.ResponseFactor.ToString(UIParamater.Cham2So);
            txtResponseSalary.Text = _SalaryInfo.ResponseSalary.ToString(UIParamater.Phay2So);
            txtComFactory.Text = _SalaryInfo.CompanyFactor.ToString(UIParamater.Cham2So);
            txtComSalary.Text = _SalaryInfo.CompanySalary.ToString(UIParamater.Phay2So);
            txtAward.Text = _SalaryInfo.Award.ToString(UIParamater.Phay2So);
            //txtLaterInsurance.Text = _SalaryInfo.LaterSalary.ToString(UIParamater.Phay2So);
            //txtOtherResponseSalary.Text = _SalaryInfo.OtherResponse.ToString(UIParamater.Phay2So);
            txtSumSalary_arisen.Text = (_SalaryInfo.BasicSalary + _SalaryInfo.PositionAllowance + _SalaryInfo.OtherResponse + _SalaryInfo.Award).ToString(UIParamater.Phay2So);

            txtComLunch.Text = _SalaryInfo.CompanyLunch.ToString(UIParamater.Phay2So);
            txtTelephoneCost.Text = _SalaryInfo.TelephoneCost.ToString(UIParamater.Phay2So);
            txtTradeUnion.Text = _SalaryInfo.TradeUnion.ToString(UIParamater.Phay2So);
            txtIncomeTax.Text = _SalaryInfo.IncomeTax.ToString(UIParamater.Phay2So);
            txtUnemployedIns.Text = _SalaryInfo.UnemployedIns.ToString(UIParamater.Phay2So);
            txtUnemployedInsCompany.Text = _SalaryInfo.UnemployedInsCompany.ToString(UIParamater.Phay2So);
            if (_SalaryInfo.EmployeeSocialInc < 0)
                txtSocialInc.Text = "";
            else
                txtSocialInc.Text = _SalaryInfo.EmployeeSocialInc.ToString(UIParamater.Phay2So);
            if (_SalaryInfo.EmployeeMedicalInc < 0)
                txtMedicalInc.Text = "";
            else
                txtMedicalInc.Text = _SalaryInfo.EmployeeMedicalInc.ToString(UIParamater.Phay2So);
            txtAdvance.Text = _SalaryInfo.Advance.ToString(UIParamater.Phay2So);
            txtOtherDeduction.Text = _SalaryInfo.OtherDeduction.ToString(UIParamater.Phay2So);
            txtSumSalary_Deduction.Text = (_SalaryInfo.IncomeTax + _SalaryInfo.OtherDeduction + _SalaryInfo.TradeUnion + _SalaryInfo.EmployeeMedicalInc + _SalaryInfo.EmployeeSocialInc + _SalaryInfo.UnemployedIns).ToString(UIParamater.Phay2So);
            txtSumSalary.Text = (Convert.ToDecimal(txtSumSalary_arisen.Text) - Convert.ToDecimal(txtSumSalary_Deduction.Text)).ToString(UIParamater.Phay2So);
            txtBHYTCty.Text = _SalaryInfo.MedicalInc.ToString("#,##0");
            txtBHXHCty.Text = _SalaryInfo.SocialInc.ToString("#,##0");
            txtTotalCost_Company.Text = (Convert.ToDecimal(txtSumSalary.Text) + _SalaryInfo.MedicalInc + _SalaryInfo.SocialInc + _SalaryInfo.UnemployedInsCompany).ToString("#,##0");
            _Isload = true;
        }

        private void Form2Info()//Chuyển dữ liệu từ form nhập vào Info
        {

            _SalaryInfo.ID = _SalaryID;
            _SalaryInfo.EmployeeID = Convert.ToInt32(txtFullName.Tag);
            if (Convert.ToInt32(cboMonth.Text) < 10)
                _SalaryInfo.Date = DateTime.ParseExact("0" + cboMonth.Text + "/" + cboYear.Text, "MM/yyyy", null);
            else
                _SalaryInfo.Date = DateTime.ParseExact(cboMonth.Text + "/" + cboYear.Text, "MM/yyyy", null);
            _SalaryInfo.ProbationFactor = Convert.ToDecimal(txtProbation.Text);

            // Thông tin làm việc:
            _SalaryInfo.TotalDateWork = Convert.ToDecimal(txtDateWork.Text);
            _SalaryInfo.TotalDateOutWork = Convert.ToDecimal(txtDateOutWork.Text);
            _SalaryInfo.TotalLeavePaid = Convert.ToDecimal(txtLeavePaid.Text);
            _SalaryInfo.TotalLeaveUnPaid = Convert.ToDecimal(txtLeaveUnPaid.Text);
            _SalaryInfo.OverTime = Convert.ToDecimal(txtOverTime.Text);

            // Tính các khoản tăng:
            //_SalaryInfo.PositionFactor = Convert.ToDecimal(txtPositionFactor.Text);
            //_SalaryInfo.BasicFactor = Convert.ToDecimal(txtBasicFactory.Text);
            _SalaryInfo.OverSeniorityFactor = Convert.ToDecimal(txtOverSeniorityFactor.Text) / 100 * _SalaryInfo.BasicFactor;
            _SalaryInfo.SeniorityFactor = Convert.ToDecimal(txtSeniorityFactor.Text) / 100 * (_SalaryInfo.BasicFactor + _SalaryInfo.OverSeniorityFactor + _SalaryInfo.PositionFactor);
            _SalaryInfo.CompanyFactor = Convert.ToDecimal(txtComFactory.Text);
            _SalaryInfo.ResponseFactor = Convert.ToDecimal(txtResponseFactory.Text);
            _SalaryInfo.BasicSalary = Convert.ToDecimal(txtBasicSalary.Text);
            _SalaryInfo.CompanySalary = Convert.ToDecimal(txtComSalary.Text);
            _SalaryInfo.ResponseSalary = Convert.ToDecimal(txtResponseSalary.Text);
            //_SalaryInfo.OtherResponse = Convert.ToDecimal(txtOtherResponseSalary.Text);

            // Tính các khoản giảm:
            _SalaryInfo.IncomeTax = Convert.ToDecimal(txtIncomeTax.Text);
            _SalaryInfo.TradeUnion = Convert.ToDecimal(txtTradeUnion.Text);
            _SalaryInfo.CompanyLunch = Convert.ToDecimal(txtComLunch.Text);
            _SalaryInfo.TelephoneCost = Convert.ToDecimal(txtTelephoneCost.Text);
            _SalaryInfo.Advance = Convert.ToDecimal(txtAdvance.Text);
            _SalaryInfo.OtherDeduction = Convert.ToDecimal(txtOtherDeduction.Text);

        }

        bool checkValid() //Kiểm tra dữ liệu nhập
        {
            decimal sal;
            if (txtProbation.Text.Trim().Length == 0)
            {
                txtProbation.Focus();
                Program.taskbarNotifier.Show(UIParamater.TitleProject, "Tỉ lệ lương không được để trống\n Hãy nhập lại", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                return false;
            }
            else
                if (!decimal.TryParse(txtProbation.Text, out sal))
                {
                    txtProbation.Text = "";
                    txtProbation.Focus();
                    Program.taskbarNotifier.Show(UIParamater.TitleProject, "Tỉ lệ lương không hợp lệ\n Hãy nhập dạng số thập phân", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                    return false;
                }
            return true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (checkValid())
            {
                SalaryClient wcfSalary = Service.Salary();
                Form2Info();
                if (_SalaryID > 0)//update
                {
                    if (!listRole.Update)
                    {
                        Program.taskbarNotifier.Show(UIParamater.TitleProject, UpdateUI.GetString("khongcoquyencapnhat"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                        return;
                    }
                    if (wcfSalary.Salary_Update(_SalaryInfo))
                    {
                        Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), UpdateUI.GetString("capnhatthanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                        dlgResult = DialogResult.OK;
                    }
                    else
                        Program.taskbarNotifier.Show(UIParamater.TitleProject, UpdateUI.GetString("capnhatkhongthanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmSalaryInfo_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    if (!e.Alt && !e.Control)
                    {
                        this.ProcessTabKey(!e.Shift);
                        e.Handled = true;
                    }
                    break;
                case Keys.Escape:
                    this.Dispose();
                    this.Close();
                    break;
                case Keys.F3:
                    btnSave_Click(null, null);
                    break;
            }
        }

        void TextChange()
        {
            if (!CheckTextValid.IsDecimal(txtDateWork.Text))
                return;
            decimal _Factor;
            _Factor = Convert.ToDecimal(txtProbation.Text);
            if (txtDateWork.Text.Trim() == "")
                txtDateWork.Text = "0";
            decimal _TotalDate = 0;
            _TotalDate = Convert.ToDecimal(txtDateWork.Text);

            wcfPD = Service.PositionDetail();
            _PDInfo = wcfPD.PositionDetail_GetInfo(_EmployeeID);

            decimal _BasicSalary = _PDInfo.BasicSalary;
            int _countDependent = 0;
            decimal _TotalFamilySalary = 0;

            MainServiceClient wcfMainService = Service.MainService();
            string _sql = "SELECT COUNT(Family_ID) AS Number FROM HRM_Family WHERE Family_EmployeeID = " + _EmployeeID + " AND Family_IsDependent = 'true'";
            DataTable dt = wcfMainService.Query(_sql).Tables[0];
            _countDependent = Convert.ToInt32(dt.Rows[0]["Number"]);
            _TotalFamilySalary = _countDependent * _FamilySalary;

            bool _IsInsurance = false;
            wcfLC = Service.LabourContract();
            DataTable dtLC = wcfLC.LabourContract_GetWithEmployee(_EmployeeID).Tables[0];
            if (dtLC.Rows.Count > 0)
                _IsInsurance = Convert.ToBoolean(dtLC.Rows[0]["ContractType_Insurance"]);

            bool _SocialEmployee = true;
            bool _MedicalEmployee = true;
            LeaveWorkClient wcfLeave = Service.LeaveWork();
            if (wcfLeave.LeaveWork_CheckExistEmployee(_EmployeeID, _month, _year))
            {
                DataTable dtFM = wcfLeave.LeaveWork_GetWithEmployee(_EmployeeID, _SalaryInfo.Date).Tables[0];
                _SocialEmployee = Convert.ToBoolean(dtFM.Rows[0]["SocialInsurance"]);
                _MedicalEmployee = Convert.ToBoolean(dtFM.Rows[0]["MedicalInsurance"]);
            }

            //Tính lương:
            BasicSalary.TinhLuongMayChamCong(_SalaryInfo, _TotalDateWork, _TotalDate + Convert.ToDecimal(txtDateOutWork.Text),
                Convert.ToDecimal(txtOverTime.Text), 0, 0, _BasicSalary, _TotalFamilySalary,
                _EmpSocialIns, _EmpMedicalIns, _ComSocialIns, _ComMedicalIns, _SocialEmployee, _MedicalEmployee,
                _TradeUnion, _UnemployedIns, _UnemployedInsCompany, 1, _IsInsurance);

            //Các khoản tăng:
            txtBasicSalary.Text = _SalaryInfo.BasicSalary.ToString(UIParamater.Phay2So);
            txtPositionAllowance.Text = _SalaryInfo.PositionAllowance.ToString(UIParamater.Phay2So);
            txtSumSalary_arisen.Text = (_SalaryInfo.BasicSalary + _SalaryInfo.PositionAllowance
                + Convert.ToDecimal(txtOtherAllowance.Text) + Convert.ToDecimal(txtAward.Text)).ToString(UIParamater.Phay2So);

            //Các khoản giảm:
            txtIncomeTax.Text = _SalaryInfo.IncomeTax.ToString(UIParamater.Phay2So);
            txtTradeUnion.Text = _SalaryInfo.TradeUnion.ToString(UIParamater.Phay2So);
            txtMedicalInc.Text = _SalaryInfo.EmployeeMedicalInc.ToString(UIParamater.Phay2So);
            txtSocialInc.Text = _SalaryInfo.EmployeeSocialInc.ToString(UIParamater.Phay2So);
            txtUnemployedIns.Text = _SalaryInfo.UnemployedIns.ToString(UIParamater.Phay2So);
            txtSumSalary_Deduction.Text = (_SalaryInfo.IncomeTax + _SalaryInfo.TradeUnion
                + _SalaryInfo.EmployeeMedicalInc + _SalaryInfo.EmployeeSocialInc
                + _SalaryInfo.UnemployedIns + _SalaryInfo.OtherDeduction).ToString(UIParamater.Phay2So);

            txtSumSalary.Text = (Convert.ToDecimal(txtSumSalary_arisen.Text) -
                Convert.ToDecimal(txtSumSalary_Deduction.Text)).ToString(UIParamater.Phay2So);

            //Công ty:
            txtBHXHCty.Text = _SalaryInfo.SocialInc.ToString(UIParamater.Phay2So);
            txtBHYTCty.Text = _SalaryInfo.MedicalInc.ToString(UIParamater.Phay2So);
            txtUnemployedInsCompany.Text = _SalaryInfo.UnemployedInsCompany.ToString(UIParamater.Phay2So);

            txtTotalCost_Company.Text = (Convert.ToDecimal(txtSumSalary.Text)
                + _SalaryInfo.SocialInc + _SalaryInfo.MedicalInc
                + _SalaryInfo.UnemployedInsCompany).ToString(UIParamater.Phay2So);

        }

        private void txtDateWork_TextChanged(object sender, EventArgs e)
        {
            if (_Isload)
            {
                TextChange();
            }
        }

        private void txtDateWork_Leave(object sender, EventArgs e)
        {
            if (_Isload)
            {
                TextChange();
            }
        }

        void textSumChange()
        {
            txtSumSalary.Text = (Convert.ToDecimal(txtSumSalary_arisen.Text) -
                Convert.ToDecimal(txtSumSalary_Deduction.Text)).ToString(UIParamater.Phay2So);

            txtTotalCost_Company.Text = (Convert.ToDecimal(txtSumSalary.Text)
                + Convert.ToDecimal(txtBHXHCty.Text) + Convert.ToDecimal(txtBHYTCty.Text)
                + Convert.ToDecimal(txtUnemployedInsCompany.Text)).ToString(UIParamater.Phay2So);
        }

        private void txtOtherAllowance_TextChanged(object sender, EventArgs e)
        {
            if (txtOtherAllowance.Text.Trim().Length == 0)
                txtOtherAllowance.Text = "0";

            txtSumSalary_arisen.Text = (Convert.ToDecimal(txtBasicSalary.Text)
                + Convert.ToDecimal(txtPositionAllowance.Text) + Convert.ToDecimal(txtOtherAllowance.Text)
                + Convert.ToDecimal(txtAward.Text)).ToString(UIParamater.Phay2So);

            textSumChange();

        }

        private void txtOtherDeduction_TextChanged(object sender, EventArgs e)
        {
            if (txtOtherDeduction.Text.Trim().Length == 0)
                txtOtherDeduction.Text = "0";

            txtSumSalary_Deduction.Text = (Convert.ToDecimal(txtIncomeTax.Text)
                + Convert.ToDecimal(txtTradeUnion.Text) + Convert.ToDecimal(txtSocialInc.Text)
               + Convert.ToDecimal(txtMedicalInc.Text) + Convert.ToDecimal(txtUnemployedIns.Text)
               + Convert.ToDecimal(txtOtherDeduction.Text)).ToString(UIParamater.Phay2So);

            textSumChange();
        }

        private void frmSalaryInfo_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult = dlgResult;
            
        }
    }
}
